﻿using Entity;
using Microsoft.AspNetCore.Http;
using ServiceCore;
using ServiceCore.Tool.NPOI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using ServiceCore.Tool;
using System.Web;
using System.IO;
using System.Data;


namespace Customer.Bussiness_Service
{

    public interface Iminiprogram_menu_service
    {
        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultListModel<miniprogram_menu> get_mini_menu_pagelist(Base_List_Params query);
        /// <summary>
        /// 保存小程序权限列表
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        ResultObjModel save_mini_menu(miniprogram_menu Params);
        /// <summary>
        /// 删除小程序菜单
        /// </summary>
        /// <param name="menu_id"></param>
        /// <returns></returns>
        ResultModel del_mini_menu(string menu_id);
        /// <summary>
        /// 获取小程序树结构数据
        /// </summary>
        /// <param name="role_id"></param>
        /// <returns></returns>
        ResultObjModel get_mini_menu_tree(string role_id);
        /// <summary>
        /// 获取角色权限
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultListModel<Role> get_role_list(Base_List_Params query);
        /// <summary>
        /// 保存权限
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        ResultObjModel save_role(create_role_params Params);
    }
    public class miniprogram_menu_service : Iminiprogram_menu_service
    {
        private readonly IToole_DI _tool;
        public miniprogram_menu_service(IToole_DI Tool)
        {
            _tool = Tool;
        }

        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <returns></returns>
        public ResultListModel<miniprogram_menu> get_mini_menu_pagelist(Base_List_Params query) {
            return CoreStartDo.ResultAction<ResultListModel<miniprogram_menu>>(result =>
            {
                string sql = "select * from miniprogram_menu";
                string where = " where 1=1";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                if (!string.IsNullOrWhiteSpace(query.SerchKeyword))
                {
                    where += " and (name like @SerchKeyword or navigate like @SerchKeyword)";
                    query_dy.SerchKeyword = $"%{query.SerchKeyword}%";
                }
                return _tool.di_db.GetRKPageList<miniprogram_menu>(sql, where, "addtime", query_dy, query.IsPage, query.page, query.pagesize);  
            });
        } 
        /// <summary>
        /// 保存小程序用权限列表
        /// </summary>
        /// <returns></returns>
        public ResultObjModel save_mini_menu(miniprogram_menu Params)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(Params.diy_menu_id))
                {
                    result.code = 1;
                    result.msg = "自定义菜单ID不能为空";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(Params.name))
                {
                    result.code = 1;
                    result.msg = "菜单名称备注不能为空";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(Params.navigate))
                {
                    result.code = 1;
                    result.msg = "设置页面跳转备注不能为空";
                    return result;
                }
                int _db_rows = 0;
                if (string.IsNullOrWhiteSpace(Params.menu_id))
                {
                    var diy_check = _tool.di_db.Get_rk_List<int>("select count(*) from miniprogram_menu  where baseuserid=@baseuserid  and diy_menu_id=@diy_menu_id", new
                    {
                        baseuserid = "RK",
                        diy_menu_id = Params.diy_menu_id
                    }).FirstOrDefault();
                    if (diy_check > 0)
                    {
                        result.code = 1;
                        result.msg = "自定义菜单ID已设置";
                        return result;
                    }
                    //当前添加
                    Params.addtime = DateTime.Now;
                    Params.baseuserid = "RK";
                    Params.menu_id = _tool.di_getid.IGet_SnowFlake_Id;
                    _db_rows = _tool.di_db.do_rk_Execute(_tool.di_db.AddBySqlStr<miniprogram_menu>(), Params);
                }
                else
                {
                    //当前编辑
                    var updateitem = _tool.di_db.Get_rk_List<miniprogram_menu>("select top 1 * from miniprogram_menu where menu_id=@menu_id", new { menu_id = Params.menu_id }).FirstOrDefault();
                    if (updateitem == null)
                    {
                        result.code = 1;
                        result.msg = "待更新数据不存在";
                        return result;
                    }
                    //验证非非当前更新项的diymenu
                    var diy_check = _tool.di_db.Get_rk_List<int>("select count(*) from miniprogram_menu  where baseuserid=@baseuserid  and diy_menu_id=@diy_menu_id and menu_id<>@menu_id", new
                    {
                        baseuserid = "RK",
                        diy_menu_id = Params.diy_menu_id,
                        menu_id = Params.menu_id
                    }).FirstOrDefault();
                    if (diy_check > 0)
                    {
                        result.code = 1;
                        result.msg = "自定义菜单ID已设置";
                        return result;
                    }
                    updateitem.diy_menu_id = Params.diy_menu_id;
                    updateitem.name = Params.name;
                    updateitem.icon = Params.icon;
                    updateitem.navigate = Params.navigate;
                    updateitem.parent_id = Params.parent_id;
                    //准备更新
                    _db_rows = _tool.di_db.do_rk_Execute("update miniprogram_menu set diy_menu_id=@diy_menu_id,name=@name,icon=@icon,navigate=@navigate,parent_id=@parent_id where menu_id=@menu_id", updateitem);
                }
                if (_db_rows > 0)
                {
                    result.code = 0;
                    result.msg = "保存成功";
                    return result;
                }
                else
                {
                    result.code = 1;
                    result.msg = "保存失败";
                    return result;
                }
            });
        }
        /// <summary>
        /// 删除小程序列表
        /// </summary>
        /// <returns></returns>
        public ResultModel del_mini_menu(string menu_id)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(menu_id))
                {
                    result.code = 1;
                    result.msg = "关键参数未入参";
                    return result;
                }
                var check_del = _tool.di_db.Get_rk_List<miniprogram_menu>("select top 1 * from miniprogram_menu where menu_id=@menu_id", new { menu_id }).FirstOrDefault();
                if (check_del == null)
                {
                    result.code = 1;
                    result.msg = "待删除项不存在";
                    return result;
                }
                string error = "";
                int tran_rows = _tool.di_db.StartRKTran((conn, tran) =>
                {
                    int rows = 0;
                    rows += conn.Execute("delete from miniprogram_menu where menu_id=@menu_id", new { menu_id }, tran);
                    rows += conn.Execute("delete from miniprogram_menu_role where diy_menu_id=@diy_menu_id", new { diy_menu_id = check_del.diy_menu_id }, tran);
                    return rows;
                }, ref error);
                if (string.IsNullOrWhiteSpace(error))
                {
                    result.code = 0;
                    result.msg = "删除成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "删除失败";
                }
                return result;
            });
        }

        /// <summary>
        ///  获取菜单树
        /// </summary>
        /// <returns></returns>
        public ResultObjModel get_mini_menu_tree(string role_id)
        {
            return CoreStartDo.ResultAction(result =>
            {
                //请求全部数据
                List<miniprogram_menu> menu_list = _tool.di_db.Get_rk_List<miniprogram_menu>("select * from miniprogram_menu", null).ToList();
                List<string> checked_array = new List<string>();
                if (!string.IsNullOrWhiteSpace(role_id))
                {
                    checked_array = _tool.di_db.Get_rk_List<string>("select diy_menu_id from miniprogram_menu_role where role_id=@role_id", new { role_id }).ToList();
                }
                List<minu_menu_tree> resultlist = new List<minu_menu_tree>();
                var q = from o in menu_list.Where(s => string.IsNullOrWhiteSpace(s.parent_id)).OrderBy(s => s.diy_menu_id)
                        select new minu_menu_tree
                        {
                            ischeck = checked_array.Contains(o.diy_menu_id),
                            IsLast = !menu_list.Where(s => s.parent_id == o.menu_id).Any(),
                            meta = new VueMenuMate()
                            {
                                title = o.diy_menu_id + "-" + o.name,
                                icon = o.icon
                            },
                            path = o.navigate,
                            name = o.diy_menu_id,
                            children = get_tree(o.menu_id, menu_list, checked_array)
                        };
                result.code = 0;
                result.msg = "success";
                result.data = new
                {
                    tree_list = q.ToList(),
                    checked_list = checked_array,
                    role_id
                };
                return result;
            });
        }

        private List<minu_menu_tree> get_tree(string parentid, List<miniprogram_menu> org_list, List<string> checked_array)
        { 
            var q = from o in org_list.Where(s => s.parent_id == parentid).OrderBy(s => s.diy_menu_id)
                    select new minu_menu_tree
                    {
                        ischeck = checked_array.Contains(o.diy_menu_id),
                        IsLast = !org_list.Where(s => s.parent_id == o.menu_id).Any(),
                        meta = new VueMenuMate()
                        {
                            title = o.diy_menu_id + "-" + o.name,
                            icon = o.icon
                        },
                        path = o.navigate,
                        name = o.diy_menu_id,
                        children = get_tree(o.menu_id, org_list, checked_array)
                    };
            return q.ToList();
        }
          
        /// <summary>
        /// 获取权限列表
        /// </summary>
        /// <returns></returns>
        public ResultListModel<Role> get_role_list(Base_List_Params query)
        {
            return CoreStartDo.ResultAction<ResultListModel<Role>>(result =>
            {
                string sql = "select * from [role]";
                string where = " where  1=1 and BaseUserId=@BaseUserId";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                query_dy.BaseUserId = "RK";
                return _tool.di_db.GetRKPageList<Role>(sql, where, "Id", query_dy, query.IsPage, query.page, query.pagesize, "asc");
            });
        }
        /// <summary>
        /// 编辑角色
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        public ResultObjModel save_role(create_role_params Params)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (Params.diy_menus == null)
                {
                    Params.diy_menus = new List<string>();
                }
                if (string.IsNullOrWhiteSpace(Params.role.Name))
                {
                    result.code = 1;
                    result.msg = "必须设置权限名称";
                    return result;
                }
                if (Params.role.Id == null)
                {
                    Params.role.Id = "";
                }
                Params.role.BaseUserId = "RK";
                int check_count = _tool.di_db.Get_rk_List<int>("select count(*) from [role] where baseuserid=@baseuserid and Id<>@Id and Name=@Name", new { baseuserid = Params.role.BaseUserId, Id = Params.role.Id, Name = Params.role.Name }).FirstOrDefault();
                if (check_count > 0)
                {
                    result.code = 1;
                    result.msg = "已存在同名角色";
                    return result;
                }
                string if_add_id = _tool.di_getid.IGet_SnowFlake_Id;
                var add_diy_menus = from o in Params.diy_menus
                               select new miniprogram_menu_role
                               {
                                   diy_menu_id = o,
                                   role_id = string.IsNullOrWhiteSpace(Params.role.Id) ? if_add_id : Params.role.Id
                               };
                string error = "";
                int tranrows = 0;
                if (string.IsNullOrWhiteSpace(Params.role.Id))
                {  
                    Params.role.IsDelete = false;
                    Params.role.UpdateOn = Params.role.CreateOn = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    Params.role.UpdateBy = Params.role.CreateBy = _tool.di_user.USER.uid;
                    Params.role.BaseUserId = "RK";
                    Params.role.Id = if_add_id;
                    tranrows = _tool.di_db.StartRKTran((conn, tran) =>
                    {
                        int rows = 0;
                        rows += conn.Execute(_tool.di_db.AddBySqlStr<Role>(), Params.role, tran);
                        rows += conn.Execute(_tool.di_db.AddBySqlStr<miniprogram_menu_role>(), add_diy_menus.ToList(), tran);
                        return rows;
                    }, ref error);
                }
                else
                {
                    var check_update = _tool.di_db.Get_rk_List<int>("select  top 1 count(*) from [role] where Id=@role_id", new { role_id = Params.role.Id }).FirstOrDefault();
                    if (check_update == 0)
                    {
                        result.code = 1;
                        result.msg = "待修改项不存在";
                        return result;
                    }
                    tranrows = _tool.di_db.StartRKTran((conn, tran) =>
                    {
                        int rows = 0;
                        rows += conn.Execute(_tool.di_db.UpdateBySqlstr<Role>(new string[] { "Name", "Remark" }, new string[] { "Id=@Id" }), Params.role, tran);
                        rows += conn.Execute("delete from miniprogram_menu_role where role_id=@Role_Id", new { Role_Id = Params.role.Id }, tran);
                        rows += conn.Execute(_tool.di_db.AddBySqlStr<miniprogram_menu_role>(), add_diy_menus.ToList(), tran);
                        return rows;
                    }, ref error);
                }
                if (string.IsNullOrWhiteSpace(error))
                {
                    result.code = 0;
                    result.msg = "保存成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "保存失败:" + error;
                }
                return result;
            });
        }
         
    }
}
